<?

if(file_exists($_SERVER["DOCUMENT_ROOT"]."/DevTools/ArrViewer.php"))
        require_once($_SERVER["DOCUMENT_ROOT"]."/DevTools/ArrViewer.php");

include_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/include/user_inc/auto_include.php");
        
require_once($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/Mn/Service/Bootstrap/Bootstrap.php');

$bootstrap = new MnServiceBootstrapBootstrap();
$bootstrap
    ->initLib()
    ->initModel()
    ->initService()
    ->initHelper()
;

/*Version 0.3 2011-04-25*/
AddEventHandler("iblock", "OnAfterIBlockElementUpdate", "BXIBlockAfterSave");
AddEventHandler("iblock", "OnAfterIBlockElementAdd", "BXIBlockAfterSave");
AddEventHandler("catalog", "OnPriceAdd", "BXIBlockAfterSave");
AddEventHandler("catalog", "OnPriceUpdate", "BXIBlockAfterSave");

//require($_SERVER["DOCUMENT_ROOT"]."/ArrViewer.php");


function BXIBlockAfterSave($arg1, $arg2 = false)
{
$ELEMENT_ID = false;
	$IBLOCK_ID = false;
	$OFFERS_IBLOCK_ID = false;
	$OFFERS_PROPERTY_ID = false;

	//Check for catalog event
	if(is_array($arg2) && $arg2["PRODUCT_ID"] > 0)
	{
		//Get iblock element
		$rsPriceElement = CIBlockElement::GetList(
			array(),
			array(
				"ID" => $arg2["PRODUCT_ID"],
			),
			false,
			false,
			array("ID", "IBLOCK_ID")
		);
		if($arPriceElement = $rsPriceElement->Fetch())
		{
			$arCatalog = CCatalog::GetByID($arPriceElement["IBLOCK_ID"]);
			if(is_array($arCatalog))
			{
				//Check if it is offers iblock
				if($arCatalog["OFFERS"] == "Y")
				{
					//Find product element
					$rsElement = CIBlockElement::GetProperty(
						$arPriceElement["IBLOCK_ID"],
						$arPriceElement["ID"],
						"sort",
						"asc",
						array("ID" => $arCatalog["SKU_PROPERTY_ID"])
					);
					$arElement = $rsElement->Fetch();
					if($arElement && $arElement["VALUE"] > 0)
					{
						$ELEMENT_ID = $arElement["VALUE"];
						$IBLOCK_ID = $arCatalog["PRODUCT_IBLOCK_ID"];
						$OFFERS_IBLOCK_ID = $arCatalog["IBLOCK_ID"];
						$OFFERS_PROPERTY_ID = $arCatalog["SKU_PROPERTY_ID"];
					}
				}
				//or iblock wich has offers
				elseif($arCatalog["OFFERS_IBLOCK_ID"] > 0)
				{
					$ELEMENT_ID = $arPriceElement["ID"];
					$IBLOCK_ID = $arPriceElement["IBLOCK_ID"];
					$OFFERS_IBLOCK_ID = $arCatalog["OFFERS_IBLOCK_ID"];
					$OFFERS_PROPERTY_ID = $arCatalog["OFFERS_PROPERTY_ID"];
				}
				//or it's regular catalog
				else
				{
					$ELEMENT_ID = $arPriceElement["ID"];
					$IBLOCK_ID = $arPriceElement["IBLOCK_ID"];
					$OFFERS_IBLOCK_ID = false;
					$OFFERS_PROPERTY_ID = false;
				}
			}
		}
	}
	//Check for iblock event
	elseif(is_array($arg1) && $arg1["ID"] > 0 && $arg1["IBLOCK_ID"] > 0)
	{
		//Check if iblock has offers
		$arOffers = CIBlockPriceTools::GetOffersIBlock($arg1["IBLOCK_ID"]);
		if(is_array($arOffers))
		{
			$ELEMENT_ID = $arg1["ID"];
			$IBLOCK_ID = $arg1["IBLOCK_ID"];
			$OFFERS_IBLOCK_ID = $arOffers["OFFERS_IBLOCK_ID"];
			$OFFERS_PROPERTY_ID = $arOffers["OFFERS_PROPERTY_ID"];
		}
	}

	if($ELEMENT_ID)
	{
		static $arPropCache = array();
		if(!array_key_exists($IBLOCK_ID, $arPropCache))
		{
			//Check for MINIMAL_PRICE property
			$rsProperty = CIBlockProperty::GetByID("MINIMUM_PRICE", $IBLOCK_ID);
			$arProperty = $rsProperty->Fetch();
			if($arProperty)
				$arPropCache[$IBLOCK_ID] = $arProperty["ID"];
			else
				$arPropCache[$IBLOCK_ID] = false;
		}

		if($arPropCache[$IBLOCK_ID])
		{
			//Compose elements filter
			$arProductID = array($ELEMENT_ID);
			if($OFFERS_IBLOCK_ID)
			{
				$rsOffers = CIBlockElement::GetList(
					array(),
					array(
						"IBLOCK_ID" => $OFFERS_IBLOCK_ID,
						"PROPERTY_".$OFFERS_PROPERTY_ID => $ELEMENT_ID,
					),
					false,
					false,
					array("ID")
				);
				while($arOffer = $rsOffers->Fetch())
					$arProductID[] = $arOffer["ID"];
			}

			$minPrice = false;
			$maxPrice = false;
			//Get prices
			$rsPrices = CPrice::GetList(
				array(),
				array(
					"BASE" => "Y",
					"PRODUCT_ID" => $arProductID,
				)
			);
			while($arPrice = $rsPrices->Fetch())
			{
				$PRICE = $arPrice["PRICE"];

				if($minPrice === false || $minPrice > $PRICE)
					$minPrice = $PRICE;

				if($maxPrice === false || $maxPrice < $PRICE)
					$maxPrice = $PRICE;
			}

			//Save found minimal price into property
			if($minPrice !== false)
			{
				CIBlockElement::SetPropertyValuesEx(
					$ELEMENT_ID,
					$IBLOCK_ID,
					array(
						"MINIMUM_PRICE" => $minPrice,
						"MAXIMUM_PRICE" => $maxPrice,
					)
				);
			}
		}
	}
}

$ContentPage=array(
"/shipping_and_payment/",
"/guaranty/",
"/dedietrich/",
"/service/",
"/help/",
"/contact/"
);

function CheckContent($where="header")
{
global $ContentPage;
global $APPLICATION;
$cpage=$APPLICATION->GetCurPage();
if(in_array($cpage,$ContentPage)):
    if($where=="header"):
        echo "<div class='contenttext'>";
    else:
        echo "</div>";
    endif;
endif;    
};

//@todo t50 integration - get all this and call from order_ready file out after testing
//beta version
//without actually adding to temp table for resend now (func exists, but empty)
function onOrderAdd($orderData)
{
    $data = convertOrderDataToStandard($orderData);
    $data = serialize($data);

    if (!requestPost('http://t50.su/ext/remote/order/add.php', array('data' => $data))) storeUnshippedOrder($data);
}

//2 person types now, 1 pay system supported
function convertOrderDataToStandard($orderData)
{
    $shopUnid = 'DDH';

    $individualPersonTypeId = 1;
    $cashPaySystemId = 1;

    $namePropId = 1;
    $phonePropId = 3;
    $emailPropId = 2;
    $cityPropId = 6;
    $addressPropId = 7;
    $deliveryDatePropId = 0;
    $commentPropId = 0;


    $data = array();

    if (!isset($orderData)) $orderData['ORDER_ID'] = $_REQUEST['ORDER_ID'];

    $order = CSaleOrder::GetByID($orderData['ORDER_ID']);

    if ($order['PERSON_TYPE_ID'] == $individualPersonTypeId) $data['PERSON_TYPE'] = 'individual';
    else
    {
        $data['PERSON_TYPE'] = 'another';

        $personType = CSalePersonType::GetByID($order['PERSON_TYPE_ID']);
        $data['PERSON_TYPE_ANOTHER'] = $personType['NAME'];
    }

    if ($order['PAY_SYSTEM_ID'] == $cashPaySystemId || $order['PAY_SYSTEM_ID'] == false) $data['PAY_SYSTEM'] = 'cash';
    else
    {
        $data['PAY_SYSTEM'] = 'another';

        $paySystem = CSalePaySystem::GetByID($order['PAY_SYSTEM_ID']);
        $data['PAY_SYSTEM_ANOTHER'] = $paySystem['NAME'];
    }

    //no delivery enabled in system now, so no id is checked
    if ($order['DELIVERY_ID'] == false) $data['DELIVERY'] = 'courier';
    else
    {
        $data['DELIVERY'] = 'another';

        $delivery = CSaleDelivery::GetByID($order['DELIVERY_ID']);
        $data['DELIVERY_ANOTHER'] = $delivery['NAME'];
    }

    $dbOrderProps = CSaleOrderPropsValue::GetOrderProps($orderData['ORDER_ID']);
    while ($arOrderProps = $dbOrderProps->GetNext())
    {
        $orderData['PROPS'][$arOrderProps['ORDER_PROPS_ID']] = $arOrderProps;
    }

    $data['PROPS']['NAME'] = $orderData['PROPS'][$namePropId]['VALUE'];
    $data['PROPS']['PHONE'] = $orderData['PROPS'][$phonePropId]['VALUE'];
    $data['PROPS']['EMAIL'] = $orderData['PROPS'][$emailPropId]['VALUE'];
    $data['PROPS']['CITY'] = $orderData['PROPS'][$cityPropId]['VALUE'];
    $data['PROPS']['ADDRESS'] = $orderData['PROPS'][$addressPropId]['VALUE'];
    $data['PROPS']['DELIVERY_DATE'] = $orderData['PROPS'][$deliveryDatePropId]['VALUE'];
    $data['PROPS']['COMMENT'] = $orderData['PROPS'][$commentPropId]['VALUE'];

    $data['ORDER_PRICE'] = $order['PRICE'];
    $data['TAX'] = $order['TAX_VALUE'];

    $data['ORDER_WEIGHT'] = 0;

    $basketProducts = array();
    $dbBasket = CSaleBasket::GetList(($b="NAME"), ($o="ASC"), array("ORDER_ID"=>$orderData['ORDER_ID']));
    while ($arBasket = $dbBasket->Fetch())
    {
        $basketProducts[] = $arBasket;

        $arBasket["WEIGHT"] = DoubleVal($arBasket["WEIGHT"]);
        $data['ORDER_WEIGHT']+= $arBasket["WEIGHT"] * $arBasket["QUANTITY"];
    }

    $products = array();
    CModule::IncludeModule("iblock");

    foreach ($basketProducts as $basketProduct)
    {
        $dbProductPre = CIBlockElement::GetByID($basketProduct['PRODUCT_ID']);
        if($arProductPre = $dbProductPre->GetNext())
        {
            $dbProduct = CIBlockElement::GetList(array(), array('INCLUDE_SUBSECTIONS' => 'Y', 'ID' => $arProductPre['ID'], 'IBLOCK_ID' => $arProductPre['IBLOCK_ID']),
                false, false, array('ID', 'NAME', 'IBLOCK_ID', 'IBLOCK_SECTION_ID', 'PROPERTY_MODEL', 'PROPERTY__UNID')
            );
            $arProduct = $dbProduct->GetNextElement();
            $product = $arProduct->GetFields();
            $products[] = array(
                'unid' => $product['PROPERTY__UNID_VALUE'], 'quantity' => $basketProduct['QUANTITY'], 'price' => $basketProduct['PRICE'],
                'currency' => $basketProduct['CURRENCY'], 'id' => $product['ID'], 'name' => $product['NAME'], 'model' => $product['PROPERTY_MODEL_VALUE'],
                'iblock_id' => $product['IBLOCK_ID'], 'iblock_section_id' => $product['IBLOCK_SECTION_ID'], 'price_type' => $basketProduct['NOTES'], 'weight' => $basketProduct['WEIGHT']
            );
        }
    }
    $data['BASKET_PRODUCTS'] = $products;

    $data['SHOP_UNID'] = $shopUnid;
    $data['BASE_LANG_CURRENCY'] = $order['CURRENCY'];
    $data['DELIVERY_PRICE'] = $order['PRICE_DELIVERY'];
    $data['TAX_PRICE'] = $order['TAX_VALUE'];
    $data['ORDER_ID'] = $orderData['ORDER_ID'];

    return $data;
}

//@todo storing unshipped orders code here
function storeUnshippedOrder($arFields)
{

}

//@todo refactor this shit and take care about fails in any ways
function requestPost($url, $postdata, $files = null)
{
    $data = "";
    $boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);

    //Collect Postdata
    foreach($postdata as $key => $val)
    {
        $data .= "--$boundary\n";
        $data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
    }

    $data .= "--$boundary\n";

    //Collect Filedata
    foreach($files as $key => $file)
    {
        $fileContents = file_get_contents($file['tmp_name']);

        $data .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$file['name']}\"\n";
        $data .= "Content-Type: image/jpeg\n";
        $data .= "Content-Transfer-Encoding: binary\n\n";
        $data .= $fileContents."\n";
        $data .= "--$boundary--\n";
    }

    $params = array('http' => array(
        'method' => 'POST',
        'header' => 'Content-Type: multipart/form-data; boundary='.$boundary,
        'content' => $data
    ));

    $ctx = stream_context_create($params);
    $fp = fopen($url, 'rb', false, $ctx);

    if (!$fp) {
        return false;
    }

    $response = @stream_get_contents($fp);
    if ($response === false) {
        return false;
    }
    return $response;
}

?>